﻿Imports System.Data.SqlClient
Public Class FormPurchaseEditor
     
    Private Sub FormPurchaseEditor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        UI.FormatDataGrid(Me.dgv)
        Me.dgv.ReadOnly = False
        For Each column As DataGridViewColumn In Me.dgv.Columns
            column.ReadOnly = True
        Next
        Me.dgv.Columns("Qty").ReadOnly = False
        Me.dgv.Columns("Price").ReadOnly = False

        Me.txtPurchaseNo.Text = NoGenerator.GenerateNewPurchaseNo()

        Me.cboStore.DisplayMember = "StoreName"
        Me.cboStore.ValueMember = "StoreId"
        Me.cboStore.DataSource = Cmd.ExecuteDataTable("SELECT * FROM Store WHERE Active=1")

        Me.cboVendor.DisplayMember = "Vendor"
        Me.cboVendor.ValueMember = "VendorId"
        Me.cboVendor.DataSource = Cmd.ExecuteDataTable("SELECT VendorId,Vendor = VendorName+' ('+Phone+')' FROM Vendor WHERE Active=1")



    End Sub

    Private Sub txtProductCode_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtProductCode.KeyDown

        If e.KeyCode <> Keys.Enter Then
            Exit Sub
        End If


        Cmd.Parameters("@Code") = Me.txtProductCode.Text
        Dim dt = Cmd.ExecuteDataTable("SELECT * FROM Product WHERE ProductCode=@Code")

        If (dt.Rows.Count = 0) Then
            ClearLine()
            BrowseProduct()
            Exit Sub
        End If

        Dim row = dt.Rows(0)
        Me.txtProductId.Text = row("ProductId")
        Me.txtProductName.Text = row("ProductName")
        Me.txtPrice.Text = row("Price")
        Me.txtQty.Text = 1
        Me.txtAmount.Text = txtPrice.Text
    End Sub

    Private Sub ClearLine()
        Me.txtProductId.Text = ""
        Me.txtProductName.Text = ""
        Me.txtQty.Text = ""
        Me.txtPrice.Text = ""
        Me.txtAmount.Text = ""
        Me.txtProductCode.Text = ""

        Me.txtProductCode.Focus()

    End Sub
    Private Sub txtQty_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtQty.TextChanged, txtPrice.TextChanged
        Dim amount As Double = Val(Me.txtPrice.Text) * Val(Me.txtQty.Text)
        Me.txtAmount.Text = amount.ToString("#,##0.00")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        BrowseProduct()
    End Sub
    Private Sub BrowseProduct()
        Dim frm As New FormProductBrowser()
        frm.txtSearch.Text = Me.txtProductCode.Text
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim row = frm.dgv.SelectedRows(0)
            Me.txtProductId.Text = row.Cells("ProductId").Value
            Me.txtProductCode.Text = row.Cells("ProductCode").Value
            Me.txtProductName.Text = row.Cells("ProductName").Value
            Me.txtPrice.Text = row.Cells("Price").Value
            Me.txtQty.Text = "1"
            Me.txtAmount.Text = Me.txtPrice.Text
        End If
    End Sub

    Private Sub btnAddLine_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddLine.Click
        '' Me.dgv.Rows.Add(Me.txtProductId.Text, Me.txtProductCode.Text, Me.txtProductName.Text, Me.txtPrice.Text, Me.txtQty.Text, Me.txtAmount.Text)
        Dim searchRow = FindProductInList(Me.txtProductId.Text)


        If searchRow Is Nothing Then
            Dim i = Me.dgv.Rows.Add()
            Dim row = Me.dgv.Rows(i)
            row.Cells("ProductId").Value = Me.txtProductId.Text
            row.Cells("ProductCode").Value = Me.txtProductCode.Text
            row.Cells("ProductName").Value = Me.txtProductName.Text
            row.Cells("Price").Value = Parse.ToDecimal(Me.txtPrice.Text)
            row.Cells("Qty").Value = Parse.ToDecimal(Me.txtQty.Text)
            row.Cells("Amount").Value = Parse.ToDecimal(Me.txtAmount.Text)
        Else
            searchRow.Cells("Qty").Value = searchRow.Cells("Qty").Value + Parse.ToDecimal(Me.txtQty.Text)
            searchRow.Cells("Price").Value = Me.txtPrice.Text
            searchRow.Cells("Amount").Value = Parse.ToDecimal(searchRow.Cells("Qty").Value) * Parse.ToDecimal(Me.txtPrice.Text)
        End If
        ClearLine()
        Me.txtSubTotal.Text = CalculateSubTotal().ToString("N2")
    End Sub
    Private Function FindProductInList(ByVal id As Int16) As DataGridViewRow
        For Each row As DataGridViewRow In Me.dgv.Rows
            If row.Cells("ProductId").Value = id Then
                Return row
            End If
        Next
        Return Nothing
    End Function

    Private Function CalculateSubTotal() As Decimal

        'Dim s As Decimal = 0
        'For i As Int16 = 0 To Me.dgv.Rows.Count - 1
        '    Dim row = Me.dgv.Rows(i)
        '    s += row.Cells("AMOUNT").Value
        'Next
        'Return s

        'Dim s As Decimal = 0
        'For Each row In Me.dgv.Rows 
        '    s += row.Cells("AMOUNT").Value
        'Next
        'Return s


        'Dim arr = "1,2,3,5,4,5,6".Split(",") 
        'Dim re = arr.Where(Function(x) x / 2 = 0).Sum(Function(x) x) 
        'var re = arr.Where(x=>x/2==0).Sum(x=>x)

        'this.dgv.Rows.Cast<DataGridViewRow>().Sum(x=> (decimal)x.Cells["AMOUNT"].Value)
        'LINQ 


        Return Me.dgv.Rows.Cast(Of DataGridViewRow).Sum(Function(x) x.Cells("AMOUNT").Value)


    End Function

    Private Sub UpdateTotal()
        Dim subtotal = Parse.ToDecimal(Me.txtSubTotal.Text)
        Dim discount = Parse.ToDecimal(Me.txtDiscount.Text)
        Dim total = subtotal - (subtotal * discount / 100.0)
        Me.txtTotal.Text = total.ToString("N2")
    End Sub

    Private Sub txtDiscount_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtDiscount.TextChanged
        UpdateTotal()
    End Sub

    Private Sub txtSubTotal_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSubTotal.TextChanged
        UpdateTotal()
    End Sub

    Private Sub RemoveLine()
        If Me.dgv.SelectedRows.Count = 0 Then
            Exit Sub
        End If
        Dim row = Me.dgv.SelectedRows(0)
        Me.dgv.Rows.Remove(row)
        Me.txtSubTotal.Text = CalculateSubTotal().ToString("N2")
    End Sub

    Private Sub dgv_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgv.KeyDown
        If e.KeyCode <> Keys.Delete Then
            Exit Sub
        End If
        RemoveLine()
    End Sub


    Private Sub លបToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles លបToolStripMenuItem.Click
        RemoveLine()
    End Sub

    

    Private Sub dgv_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv.CellValueChanged
        If e.RowIndex = -1 Then
            Exit Sub
        End If

        Dim row = Me.dgv.Rows(e.RowIndex)
        Dim qty As Decimal = row.Cells("Qty").Value
        Dim price As Decimal = row.Cells("Price").Value
        Dim amount = qty * price
        row.Cells("Amount").Value = amount
        Me.txtSubTotal.Text = CalculateSubTotal().ToString("N2")
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Try
            Cmd.Begin()
            Cmd.Parameters("@PurchaseNo") = Me.txtPurchaseNo.Text
            Cmd.Parameters("@PurchaseDate") = Me.dtpDate.Value
            Cmd.Parameters("@VendorId") = Me.cboVendor.SelectedValue
            Cmd.Parameters("@StoreId") = Me.cboStore.SelectedValue
            Cmd.Parameters("@SubTotal") = Parse.ToDecimal(Me.txtSubTotal.Text)
            Cmd.Parameters("@Discount") = Parse.ToDecimal(Me.txtDiscount.Text)
            Cmd.Parameters("@Total") = Parse.ToDecimal(Me.txtTotal.Text)
            Cmd.ExecuteNonQuery("INSERT INTO Purchase VALUES(@PurchaseNo,@PurchaseDate,@VendorId,@StoreId,@Subtotal,@Discount,@Total,1);")

            Dim id = Cmd.ExecuteScalar("SELECT Max(PurchaseId) FROM Purchase;")

            For Each row As DataGridViewRow In Me.dgv.Rows
                Cmd.Parameters("@PurchaseId") = id
                Cmd.Parameters("@ProductId") = row.Cells("ProductId").Value
                Cmd.Parameters("@Qty") = row.Cells("Qty").Value
                Cmd.Parameters("@Price") = row.Cells("Price").Value
                Cmd.Parameters("@Amount") = row.Cells("Amount").Value
                Cmd.ExecuteNonQuery("INSERT INTO PurchaseDetail VALUES(@PurchaseId,@ProductId,@Qty,@Price,@Amount,1);")
            Next
           
            Cmd.Commit()

        Catch ex As Exception
            Cmd.Rollback()
            MsgBox(ex.Message)
        End Try
       
        Me.Close()

    End Sub


   
  
    Private Sub លបទងអសឪToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles លបទងអសឪToolStripMenuItem.Click
        Me.dgv.Rows.Clear()
        Me.txtSubTotal.Text = CalculateSubTotal().ToString("N2")
    End Sub

    
End Class